package com.baor.service.impl;

import Util.HttpRequestUtil;
import Util.WeChatGetUserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baor.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${wechat.secret}")
    private String secret;
    @Value("${wechat.appId}")
    private String appId;

    @Override
    public String login(Map<String, Object> params) {
        String code = params.get("code").toString();
        //TODO 访问微信获取openId
        String forObject = restTemplate.getForObject("""
                https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code
                """.formatted(appId, secret, code), String.class);
        System.out.println(forObject);
        return forObject;
    }

    @Override
    public String getPhoneNumber(Map<String,Object> params) {
        //获取Access_token
        String param = """
               grant_type=client_credential&appid=%s&secret=%s
                """.formatted(appId, secret);
        String res = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", param);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = jsonObject.get("access_token").toString();
        JSONObject object = new JSONObject();
        object.put("code",params.get("code").toString());
        String phoneNumber = HttpRequestUtil.sendPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, object.toJSONString(), null);
        JSONObject phoneNumberJson = JSON.parseObject(phoneNumber);
        return phoneNumberJson.getJSONObject("phone_info").toJSONString();
    }

    @Override
    public String getUserInfo(Map<String, Object> params) {
        String encryptedData = params.get("encryptedData").toString();
        String iv = params.get("iv").toString();
        String sessionKey = params.get("session_key").toString();
        String userInfo = WeChatGetUserInfo.decrypt(encryptedData, "3P0z3hHPG9Dhs/GsdkbRnw==", iv, "UTF-8");
        System.out.println(userInfo);

        return "";
    }
}
